//
//  OMOrderSubmitViewController.m
//  OMENGO
//
//  Created by 梁尚嘉 on 2016/12/28.
//  Copyright © 2016年 Kamfat. All rights reserved.
//

#import "OMOrderSubmitViewController.h"
#import "OMOrderSubmitProductTableCell.h"
#import "OMCartProduct.h"
#import "OMOrderBookResponse.h"
#import "KTEleCheckboxTableCell.h"
#import "OMOrderSubmitGoodListTableCell.h"
@interface OMOrderSubmitViewController ()
/** 配送时间*/
@property (nonatomic, strong) KTEleInputTableCell *timeCell;
/** 备注*/
@property (nonatomic, strong) KTEleInputTableCell *remarkCell;
/** 发票抬头*/
@property (nonatomic, strong) KTEleInputTableCell *invoiceTitleCell;
/** 发票内容*/
@property (nonatomic, strong) KTEleInputTableCell *invoiceContentCell;
/** 支付方式(在线支付，货到付款等等)*/
@property (nonatomic, strong) KTEleCheckboxTableCell *payMethodCell;
/** 商品清单*/
@property (nonatomic, strong) OMOrderSubmitGoodListTableCell *listCell;

@end

@implementation OMOrderSubmitViewController

- (void)configure
{

    [self.tableView registerClass:[OMOrderSubmitGoodListTableCell class]
           forCellReuseIdentifier:[OMOrderSubmitGoodListTableCell cellIdentifier]];
    [super configure];

    self.title = @"订单结算";

    self.addressCell = [OMCommonAddressTableCell new];

    self.timeCell = [KTEleInputTableCell new];
    self.timeCell.elementLabel.text = @"送货时间";
    self.timeCell.inputTF.placeholder = @"请选择您期待的送货时间";
    self.timeCell.inputTF.enabled = NO;
    self.timeCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    self.timeCell.inputTF.textAlignment = NSTextAlignmentRight;
    self.timeCell.canHighLight = YES;
    self.timeCell.inputTF.text = [NSDate dateStringWithFormat:@"yyyy-MM-dd HH:mm:ss" withDate:[NSDate dateWithTimeIntervalSinceNow:3600]];

    self.couponCell = [KTEleInputTableCell new];
    self.couponCell.elementLabel.text = @"优惠券";
    //    self.couponCell.inputTF.placeholder = @"无可用优惠券";
    self.couponCell.inputTF.enabled = NO;
    self.couponCell.inputTF.textAlignment = NSTextAlignmentRight;
    self.couponCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    self.couponCell.canHighLight = YES;

    self.remarkCell = [KTEleInputTableCell new];
    self.remarkCell.elementLabel.text = @"备注";
    self.remarkCell.inputTF.textAlignment = NSTextAlignmentRight;
    self.remarkCell.inputTF.placeholder = @"请填写要补充的内容";

    self.invoiceTitleCell = [KTEleInputTableCell new];
    self.invoiceTitleCell.elementLabel.text = @"发票抬头";
    self.invoiceTitleCell.inputTF.textAlignment = NSTextAlignmentRight;
    self.invoiceTitleCell.inputTF.placeholder = @"请输入发票抬头(选填)";
    self.invoiceContentCell = [KTEleInputTableCell new];
    self.invoiceContentCell.elementLabel.text = @"发票内容";
    self.invoiceContentCell.inputTF.textAlignment = NSTextAlignmentRight;
    self.invoiceContentCell.inputTF.placeholder = @"请输入发票内容(选填)";


    self.listCell = [OMOrderSubmitGoodListTableCell new];
    [self.listCell configureCellWithObj:_orderBookResponse];

    _payMethodCell = [KTEleCheckboxTableCell tableViewCellWithTableView:self.tableView];
    _payMethodCell.elementLabel.text = @"支付方式";

    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(self.navigationBar.mas_bottom);
    }];

    UIView *bottomBar = [UIView new];
    bottomBar.backgroundColor = SM_whiteColor;
    [self.view addSubview:bottomBar];
    [bottomBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(@0);
        make.top.equalTo(self.tableView.mas_bottom);
        make.height.equalTo(@(49));
    }];


    [bottomBar addSubview:self.prizeLabel];
    [bottomBar addSubview:self.confirmButton];
    [self.confirmButton setTitle:@"提交订单" forState:UIControlStateNormal];
    self.prizeLabel.textAlignment = NSTextAlignmentRight;
    UIView *line = [UIView new];
    line.backgroundColor = HEXCOLOR(@"F7F7F7");
    [bottomBar addSubview:line];


    self.prizeLabel.textAlignment = NSTextAlignmentRight;
    [self.prizeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.equalTo(@0);
        make.top.equalTo(@1);
        make.width.equalTo(@(SM_SCREEN_WIDTH/3.f*2-SM_SIZE(30)));
    }];
    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.equalTo(@0);
        make.top.equalTo(@1);
        make.left.equalTo(self.prizeLabel.mas_right).offset(SM_SIZE(30));
        make.width.equalTo(@(SM_SCREEN_WIDTH/3.f*1));
    }];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(@0);
        make.height.equalTo(@.8);
    }];

    self.prizeLabel.numberOfLines = 2;
    self.deliveryInfo = self.deliveryInfo;
    self.selectedCoupon = self.selectedCoupon;
    if (self.orderBookResponse) {
        self.deliveryInfo = self.orderBookResponse.defaultReceiver;
        [self setupCellArrayNeedInvoice:self.orderBookResponse.isInvoiceEnabled];
        NSMutableArray *titles = [@[] mutableCopy];
        NSUInteger index = 0;
        for (OMPaymentMethod *method in self.orderBookResponse.paymentMethods) {
            [titles addObject:method.name];
            if (method.isDefault) {
                index = [self.orderBookResponse.paymentMethods indexOfObject:method];
                break;
            }
        }
        _payMethodCell.titles = titles;
        if (index <titles.count) {
            self.payMethodCell.selectedIndex = index;
        }
    }else {
        [self setupCellArrayNeedInvoice:NO];
    }
    [self setPrize];

    @weakify(self);
    [SMNotificationMonitorRACSignal(OMDELIVERY_ADDRESS_DELETE_NOTIFICATION) subscribeNext:^(id x) {
        @strongify(self);
        [self setDeliveryInfo:nil];
    }];

    //    [OMFakeAction fakeLoadDataActionWithController:self];

}

- (void)setupCellArrayNeedInvoice:(BOOL)needInvoice{
    if (!needInvoice) {
        _cellArray = @[
                       @[
                           self.addressCell,
                           ],
                       @[
                           self.payMethodCell,
                           self.couponCell,
                           ],

                       @[
                           self.listCell,
                           self.remarkCell,
                           ],
                       ];
    }else {
        _cellArray = @[
                       @[
                           self.addressCell,
                           ],
                       @[
                           self.payMethodCell,
                           self.couponCell,
                           ],
                       @[
                           self.invoiceTitleCell,
                           self.invoiceContentCell,
                           ],
                       @[
                           self.listCell,
                           self.remarkCell,
                           ],
                       ];
    }
}

- (void)setPrize
{
    CGFloat prize = 0;
    for (id<OMProductProtocol> product in self.objectArray) {
        prize += [[product price] floatValue]*[product quantity];
    }
    prize -= self.selectedCoupon.price+self.orderBookResponse.order.promotionDiscount;
    [self setPrize:[NSString stringWithFormat:@"%.2f",prize]];
}

- (void)setPrize:(NSString *)price
{
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc]initWithString:[@"合计：￥" stringByAppendingString:price] attributes:@{NSForegroundColorAttributeName:SM_redColor}];
    NSRange rangOfPre = [attri.string rangeOfString:@"合计："];
    if (rangOfPre.length) {
        [attri addAttributes:@{NSForegroundColorAttributeName:SM_blackColor} range:rangOfPre];
    }
    if (self.selectedCoupon || self.orderBookResponse.order.promotionDiscount) {
        NSAttributedString *cheapAttri = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"\n已优惠：￥-%.2f",self.selectedCoupon.price+self.orderBookResponse.order.promotionDiscount] attributes:@{NSFontAttributeName:SM_CFont(28),NSForegroundColorAttributeName:SM_grayColor}];
        [attri appendAttributedString:cheapAttri];
    }
    self.prizeLabel.attributedText = attri;
}

- (void)setDeliveryInfo:(OMDeliveryInfo *)deliveryInfo
{
    _deliveryInfo = deliveryInfo;
    [self.addressCell configureCellWithObj:self.deliveryInfo];
    [self setPrize];
}


- (void)setSelectedCoupon:(OMCheapModel *)selectedCoupon
{
    [super setSelectedCoupon:selectedCoupon];
    [self updateGoodList];

    if (self.selectedCoupon) {
        self.couponCell.inputTF.text = selectedCoupon.name;
    }else {
        if (self.orderBookResponse.couponCodeCount) {
            self.couponCell.inputTF.attributedText = [[NSAttributedString alloc]initWithString:@"有可用优惠券" attributes:@{NSForegroundColorAttributeName:SM_redColor}];
        }else {
            self.couponCell.inputTF.text = self.coupons.count ? @"未使用优惠券" : @"无可用优惠券";
        }
    }
    [self setPrize];
}

- (void)updateGoodList
{
    self.orderBookResponse.order.couponDiscount = _selectedCoupon.price;
    [self.listCell configureCellWithObj:_orderBookResponse];
}

- (NSArray *)objectArray
{
    if (self.products.count) {
        return self.products;
    }else if (self.consumerGoods.count)
    {
        return self.consumerGoods;
    }else if (self.cartProducts.count)  {
        return self.cartProducts;
    }
    return self.orderBookResponse.order.orderItems;
}

#pragma mark - UITableView delegate && datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.cellArray[section] count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _cellArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return _cellArray[indexPath.section][indexPath.row];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.cellArray[indexPath.section][indexPath.row] isKindOfClass:[OMOrderSubmitGoodListTableCell class]]) {
        return [tableView fd_heightForCellWithIdentifier:[OMOrderSubmitGoodListTableCell cellIdentifier] configuration:^(OMOrderSubmitGoodListTableCell *cell) {
            [cell configureCellWithObj:self.orderBookResponse];
        }];
    }else {
        return [[_cellArray[indexPath.section][indexPath.row] class] cellHeight];
    }
    return 0;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    id cell = self.cellArray[indexPath.section][indexPath.row];

    if ([cell isKindOfClass:[OMPropertyTrackByTableCell class]])
    {
        NaviPush(@"OMDeliveryAddressViewController", @{@"delegate":self});
    }
    /*else if (indexPath.section == 1)
     {
     XZLDatePickerView * pickerView = [XZLDatePickerView customPickerView];
     pickerView.datePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:60*60];
     @weakify(pickerView);
     [pickerView setOnclick:^(NSDate *date) {
     @strongify(self);@strongify(pickerView);
     self.timeCell.inputTF.text = [NSDate dateStringWithFormat:@"yyyy/MM/dd HH:mm" withDate:pickerView.datePicker.date];
     }];
     [pickerView showInView:SMKeyWindow];
     }*/
    else if (indexPath.section == 1 && indexPath.row == 1) {
        //选择优惠券
        [self gotoSelectCoupon];
    }

}


#pragma mark - Network
/**
 ==创建订单==

 token	必选	无
 receiverId	必选	收货人地址Id
 paymentMethodId	必选	支付方式Id
 shippingMethodId	必选	配送方式Id
 source	必选	订单来源：PC，H5，IOS，ANDROID
 code	可选	优惠码
 invoiceTitle	可选	发票抬头
 invoiceContent	可选	发票内容
 memo	可选	订单备注
 isBalance	可选	是否使用余额
 shippingDate	可选	配送时间

 */
- (void)submitAction:(UIButton *)button
{

    if (!self.deliveryInfo.address.length) {
        [OMHUD HUDInfo:@"请选择收货地址"];
        return;
    }

    self.requestUrl = @"order/create.jhtml";
    OMPaymentMethod *method = self.orderBookResponse.paymentMethods[self.payMethodCell.selectedIndex];
    [self submitWithParameters:@{
                                 @"receiverId":self.deliveryInfo.id,
                                 @"paymentMethodId":method.id,
                                 @"shippingMethodId":@"1",
                                 @"code":self.selectedCoupon?self.selectedCoupon.code:@"",
                                 @"shippingDate":self.timeCell.inputTF.text.length?self.timeCell.inputTF.text:@"",
                                 @"memo":self.remarkCell.inputTF.text.length?self.remarkCell.inputTF.text: @"",
                                 @"source":@"IOS",
                                 @"invoiceTitle":self.invoiceTitleCell.inputTF.text?:@"",
                                 @"invoiceContent":self.invoiceContentCell.inputTF.text?:@"",
                                 @"cartToken":self.orderBookResponse.cartToken,
                                 @"paymentName":method.name,
                                 }];
}
@end
